# 4.提示用户输入地址，当用户输入地址后，向用户显示"欢迎您来到**"
# 输入函数： 接受用户输入
# 输出函数： 将计算结果输出
# 使用变量address 来存储 用户通过input输入的信息
# address = input("请输入地址")
# print 可以打印任意多个内容  sep 指明分隔字符串   end 指明结束字符串
# print(address, "======", "-----", 123, 46, sep="-----", end="***")
# 使用变量 存储 计算address的长度
# length = len(address)
# print(f"欢迎来到{address}, 总共输入字符{length}个")
import random

# 5.让用户分别输入姓名，语文，数学，英语 三门课的成绩，然后给用户显示：XX，你的总成绩为XX分，平均成绩为XX分
# 使用四个变量来存储用户输入的四个数据
# 断点 ： 启动调试  程序执行到这一行会 中断执行  可以进入调试
# 蓝色： 将要执行   在调试的过中 观察程序的执行情况
# username = input("输入姓名")
# cn = input("输入语文成绩")
# math = input("输入数学成绩")
# en = input("输入英语成绩")

# cn_num = float(cn)
# # print(type(cn), type(cn_num))
# math_num = float(math)
# en_num = float(en)

# 五种基本数据类型 100 int  3.14 float  True/False bool  "hello"  str  None
# total = cn_num + math_num + en_num
# avg = total / 3
# print(f"{username}, 你的总成绩是{total},  平均成绩是{avg}")


# 6.编写一个程序，输入梯形的上底 下底 和高 ，计算出来梯形的面积并显示出来。
# range（start, stop: 不包含, step步长）
# lenth = range(1, 11, 3)
# print(lenth)
# # 每循环一次i都被赋予不同的值
# for i in lenth:
#     print(f"当前i的值是{i}")
#     top = input("输入上底")
#     bottom = input("输入下底")
#     height = input("输入高")
#
#     top_num = float(top)
#     bottom_num = float(bottom)
#     height_num = float(height)
#
#     area = (top_num + bottom_num) * height_num / 2
#     print(f"梯形面积是{area}")


# 7.接受用户输入的两个整数，存储到两个变量里面，交换变量存储的值
# first = input("输入第一个数字")
# second = input("输入第二个数字")
# print(f"第一个数字是 {first} 第二个数字是 {second}")
# temp = first
# first = second
# second = temp
# print(f"交换之后first： {first} second：{second}")


# 8.从键盘输入一个三位的正整数，把百分位十分位个位数字的相反顺序组成新的三位数输出

# value = 456
# first = value // 100
# second = value // 10 % 10
# third = value % 10
# print(f"{value} 逆序以后是 {third*100+second*10+first}")

# value = str(value)
# value = list(value)
# value.reverse()
# value = "".join(value)
# print(value)


# 9.编程实现计算输入指定的天数(如46天)是几周零几天

# value = 46
# print(f"{value}是{value//7}周{value%7}天")
# # result = divmod(value, 7)
# print(result)


# 10.让用户输入一个月份，判断这个月是哪个季节？假定3到4月是春季，5到8月是夏季，	9到10是秋季，11、12、1、2月是冬季，输入其他内容不合法

# value = input("输入月份")
# if value == "3" or value == "4":
#    print(f"春季")
# elif value == "5" or value == "6" or value == "7" or value == "8":
#    print(f"夏季")
# elif value == "9" or value == "10":
#    print(f"秋季")
# elif value == "11" or value == "12" or value == "1" or value == "2":
#    print(f"冬季")
# else:
#     print(f'输入不合法')

# b = True
# while b:
#     value = input("输入月份")
#     if value in ["3", "4"]:
#         print(f"春季")
#     elif value in ["5", "6", "7", "8"]:
#         print(f"夏季")
#     elif value in ["9", "10"]:
#         print(f"秋季")
#     elif value in ["11", "12", "1", "2"]:
#         print(f"冬季")
#     else:
#         print(f'输入不合法')
#         b = False

# 11.请用户输入两次，每次输入一个数字，如果用户输入的第一个数大就输出第一个数，如果用户输入的第二个数大就输出第二个数

# first = input("输入第一个数字")
# second = input("输入第二个数字")
# if first > second:
#     print(first)
# else:
#     print(second)

# 如果first > second  则将first赋予result   否则 将second赋予result
# result = first if first > second else second
# print(result)

# 请输入10个数字  打印 最大的数与最小的数的差

# max_value = None
# min_value = None
#
# for i in range(10):
#     value = input("输入数字")
#     value = float(value)
#     # print(f"你输入的是{value}")
#     if max_value is None:
#         max_value = value
#     else:
#         if max_value < value:
#             max_value = value
#
#     if min_value is None:
#         min_value = value
#     else:
#         if min_value > value:
#             min_value = value
# print(f"  最大值{max_value} 最小值{min_value} 差值{max_value-min_value}")


# 12.提示用户输入年龄，
# 如果大于等于18，则告知用户可以查看，
# 如果小于10岁，则告知不允许查看，
# 如果大于等于10岁并且小于18，则提示用户是否继续查看（yes、no），
# 如果输入的是yes则提示用户请查看，否则提示"退出,你放弃查看"。

# age_str = input("请输入年纪")
# age_value = int(age_str)
# if age_value >= 18:
#     print(f"可以查看")
# elif age_value < 10:
#     print(f"不允许查看")
# # elif 10 <= age_value < 18:
# #     pass
# else:
#     input_value = input("是否继续查看，yes（继续） no（退出）")
#     if input_value == "yes":
#         print(f"查看")
#     elif input_value == "no":
#         print(f"退出")


# age = int(input("请输入年纪"))


# 逻辑运算符 优先级 not>and>or
# 13.编写一个程序，接受用户输入的年份，判断该年份是否为闰年。闰年的条件是：能被4整除但不能被100整除，或者能被400整除。
# year = 1900
# if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
#     print("闰年")


# python 中and 以及 or的结果是返回左侧或者右侧
# and 左侧为真 返回右侧   左侧为假 返回左侧
# or 左侧为真 直接返回左侧  左侧为假 返回右侧
# not 返回True或者False
# print(10 and 20)
# print(10 and 0)
# print(0 and 10)
# print(-100 and 200)
# print(False and 10)
# print("" and 10)
# print("0" and 10)
# print("False" and 10)
# print(None and 10)
# print([] and 100)
#
# print("============")
# print(0 or 100)
# print("hello" or False)
# print("" or False)
#
# print("=====")
# print(not 100)
# print(not [])
# print(not 0)
#
# print("============")
# print(10 and 20 or 100)
# print(200 or False and 100)
# print(100 and not 0)


# 14.在400--500之间求一个数,它被2除余1,被5除余3,被9除余1,这个数是多少?
# 400-500 之间
# 能被3 整除
# 最大的5个数
# 的和

# current = 500
# stop = 400
# count = 0
# total = 0
# while current >= stop:
#     if current % 3 == 0:
#         count += 1
#         total += current
#         print(current)
#         if count == 5:
#             break
#     current -= 1
# print(total)


# count = 0
# total = 0
# for i in range(500, 399, -1):
#     if i % 3 == 0:
#         total += i
#         count += 1
#         if count == 5:
#             break
# print(total)


# 15.编程求一个四位自然数ABCD,它乘以A后变成DCBA

# start = 1000
# while start < 10000:
#     # 4567
#     first = start // 1000
#     second = start // 100 % 10
#     third = start // 10 % 10
#     four = start % 10
#     if start * first == four * 1000 + third * 100 + second * 10 + first:
#         print(start, "===")
#     start += 1


# 16.求1-100间的所有奇数和，如果是5的倍数则不参与求和计算。
# total = 0
# for i in range(1, 101):
#     if i % 2 != 0 and i % 5 != 0:
#         total += i
# print(total)


# 17.一个自然数与3的和是5的倍数,与3的差是6的倍数,1000以内这样的自然数有几个?

# count = 0
# for i in range(1001):
#     if (i + 3) % 5 == 0 and (i - 3) % 6 == 0:
#         print(i)
#         count += 1
# print(count)


# 18.计算1-100之间所有
# 能被3整除但是不能被5整除
# 的所有数的
# 平均数
# total = 0
# count = 0
# for i in range(1, 101):
#     if i % 3 == 0 and i % 5 != 0:
#         total += i
#         count += 1
# print(total / count)


# 19.输入一个数计算该数的阶乘
# 5！=5*4*3*2*1


# 19.输入一个数计算该数的和
# 5=5+4+3+2+1

# total = 0
# for j in range(1, 5+1):
#
#     # 求j的阶乘
#     mult = 1
#     for i in range(1, j + 1):
#         mult = i * mult
#
#
#     # 累加阶乘和
#     total += mult
# print(total)

# 22.输入数字n求n的阶乘和   5的阶乘和 =5！+4！+3！+2！+1！


# 20.在400--500之间求一个数,它被2除余1,被5除余3,被9除余1,这个数是多少?

# count = 0
# for i in range(5000, 399, -1):
#     if i % 2 == 1 and i % 5 == 3 and i % 9 == 1:
#         print(i)
#         count += 1
#         if count == 3:
#             break


# 21.扩展，打印9*9乘法表（for循环嵌套）

# for i in range(1, 10):
#     # 内层循环变化一轮 外层循环变化一次
#     for j in range(1, i + 1):
#         print(f"{j} * {i} = {i * j}", end="\t")
#     print()

# 22.输入数字n求n的阶乘和   5的阶乘和 =5！+4！+3！+2！+1！

# 23.9行9列的图形，控制各种显示各种位置三角形
# for i in range(1, 10):
#     for j in range(1, 10):
#         print("*", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i == j:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i + j == 10:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i + j == 10 or i == j:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i >= j:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i + j <= 10:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i <= j and i + j >= 10:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()
#
# for i in range(1, 10):
#     for j in range(1, 10):
#         if i <= j and i + j >= 10 or i >= j and i + j <= 10:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#     print()

# 24.输入3打印
# *
# ***
# *****

# value = 5
# for i in range(value):
#     # print((i * 2 + 1) * "*")
#     for j in range(2*i+1):
#         print("*", end="")
#     print()


# 25.已知两个三位数abc和cba之和为1333（即abc+cba=1333）求 a、b、c
# for i in range(100, 1000):
#     # 456
#     first = i // 100
#     second = i // 10 % 10
#     third = i % 10
#     if i + third * 100 + second * 10 + first == 1333:
#         print(i)

# for a in range(1, 10):
#     for b in range(0, 10):
#         for c in range(0, 10):
#             if 100 * a + 10 * b + c + 100 * c + 10 * b + a == 1333:
#                 print(a, b, c)


# for i in range(100, 1000):
#     i_str = str(i)
#     if i + int(i_str[2] + i_str[1] + i_str[0]) == 1333:
#         print(i)


# 26.编程求出满足以下条件的三位数:它除以11所得的商等于它各位数字之和.

# current = 100
# while current < 1000:
#     first = current // 100
#     second = current // 10 % 10
#     third = current % 10
#     if current // 11 == first + second +third:
#         print(current)
#     current += 1


# 27.求1000以内最大的5个能同时被3和6整除的数。
# r = range(1000)
# print(r)
# r1 = list(r)
# print(r1)


# for i in range(1000, 0, -1):
#     print(i)

# current = 1000
# count = 0
# items = []
# while current > 0:
#     if current % 3 == 0 and current % 6 == 0:
#         count += 1
#         items.append(current)
#         if count == 5:
#             break
#     current -= 1
# print(items)

# 27 如何判定一个数字是不是质数
# 只需要 从2开始到这个数减-1  这些数字是否能够除尽
# 9
# 2 3 4 5 6 7 8

# value = 9
# for i in range(2, value):
#     if value % i == 0:
#         print(f"{i} 是{value}的因子", f"{value}不是质数")
#         break
# else:
#     # 当for循环正常结束  没有触发break
#     print(f"{value}是质数")


# 28.输入一个数字，如果这个数字是质数则打印该数字，否则则打印该数字最大的因数

# 8
# 7 6 5 4 3 2

# value = 7
# for i in range(value-1, 1, -1):
#     if value % i == 0:
#         print(f"{i}  是{value} 的最大因子")
#         break
# else:
#     print(f"{value}  是质数")


# 29.求1000以内所有质数的平均数

# total = 0
# count = 0
# for value in range(2, 1000):
#     for i in range(2, value):
#         if value % i == 0:
#             # print(f"{value}不是质数")
#             break
#     else:
#         print(f"{value}是质数")
#         total += value
#         count += 1
# print(total / count)


# 30.使用for与while两种方法,计算500-1000以内能被3整除的数的个数

# count = 0
# for i in range(500, 1001):
#     if i % 3 == 0:
#         count += 1
# print(count)

# current = 500
# count = 0
# while current <= 1000:
#     if current % 3 == 0:
#         count += 1
#     current += 1
# print(count)

# 31.打印所有的水仙花数

# current = 100
# while current < 1000:
#     # 456
#     first = current // 100
#     second = current // 10 % 10
#     third = current % 10
#     if first ** 3 + second ** 3 + third ** 3 == current:
#         print(current)
#     current += 1


# 32.输入10个数字， 打印输入数字最大值与最小值的差
# max_value = None
# min_value = None
# for i in range(10):
#     value_str = input("输入数字")
#     value = int(value_str)
#     if max_value is None:
#         max_value = value
#     else:
#         if max_value < value:
#             max_value = value
#
#     if min_value is None:
#         min_value = value
#     else:
#         if min_value > value:
#             min_value = value
# print(f"{max_value} {min_value} {max_value - min_value}")


# l0 = [-10, 50, -50, 5, 2, 9, 45, 20, -30, 30]
# max_value = l0[0]
# min_value = l0[0]
# for i in range(1, len(l0)):
#     if max_value < l0[i]:
#         max_value = l0[i]
#
#     if min_value > l0[i]:
#         min_value = l0[i]
#
# print(max_value, min_value, max_value-min_value)


# 33.使用for与while两种方法求1000以内最大的10个质数的平均数

# count = 0
# for value in range(1000, 1, -1):
#     for i in range(2, value):
#         if value % i == 0:
#             break
#     else:
#         print(f"{value}是质数")
#         count += 1
#         if count == 10:
#             break

# value = 1000
# count = 0
# while value > 1:
#     current = 2
#     while current < value:
#         if value % current == 0:
#             break
#         current += 1
#     else:
#         print(f"{value} 是质数")
#         count+=1
#         if count == 10:
#             break
#     value -= 1


# 34.随机10个不同的位于10-30之间的数放入数组，总共随机了多少次
# import random
# count = 0
# datas = []
# while len(datas) < 10:
#     value = random.randint(10, 30)
#     count += 1
#     if value not in datas:
#         datas.append(value)
# print(datas, count)


# import random
#
# datas = []
# count = 0
# while True:
#     value = random.randint(10, 30)
#     count += 1
#     if value not in datas:
#         datas.append(value)
#         if len(datas) == 10:
#             break
# print(datas, count)


# 35.一个五位数,若在它的后面写上一个7,得到一个六位数A,若在它前面写上一个7,得到一个六位数B,B是A的五倍,求此五位数
# for i in range(10000, 100000):
#     # 712345
#     if (i * 10 + 7) * 5 == 700000 + i:
#         print(i)

# 36.随机生成5-10之间的数字，直到所有数字之和大于100，计算随机的次数
# import random
# total = 0
# count = 0
# while True:
#     value = random.randint(5, 10)
#     count += 1
#     print(value)
#     total += value
#     if total > 100:
#         break
# print(total, count)


# import random
# total = 0
# count = 0
# while total <= 100:
#     value = random.randint(5, 10)
#     count += 1
#     print(value)
#     total += value
#
# print(total, count)


# 37.找出1000以内所有的完数（所有因子之和等于本身）
# for i in range(1, 1001):
#     total = 0
#     for j in range(1, i):
#         if i % j == 0:
#             total += j
#     if i == total:
#         print(i)


# 7
# 1 2 3 4 5 6

# 36. 找到字符串中出现次数最多的一个字符
# s0 = "hello world"
# result = {}
# for c in s0:
#     if c not in result:
#         result[c] = 1
#     else:
#         result[c] += 1
# # print(result)
#
# max_value = 0
# max_char = None
# for k,v in result.items():
#     if max_value < v:
#         max_value = v
#         max_char = k
#
# print(max_char, max_value)

# s0 = "hello world"
# max_value = 0
# max_char = None
# for c in s0:
#     count = s0.count(c)
#     # print(c, count)
#     if max_value < count:
#         max_value = count
#         max_char = c
# print(max_value, max_char)


# 37. 输入一个数字如果是质数则打印，然后结束程序， 否则继续输入直到输入为质数

# while True:
#     value = input("输入数字")
#     value = int(value)
#     current = 2
#     while current < value:
#         if value % current == 0:
#             break
#         current += 1
#     else:
#         print(f"{value} 是质数")
#         break


# 38.找到1000以内相差为6的质数对（5,11）（7,13）...


# 最外层循环取到2-994
# for i in range(2, 1000-6):
#     # 判定i是否为质数
#     for j in range(2, i):
#         if i % j == 0:
#             break
#     else:
#         # 判定i+6
#         # print(f"{i}是质数, 需要继续判定{i+6}是否为质数")
#         for k in range(2, i+6):
#             if (i+6) % 2 == 0:
#                 break
#         else:
#             print(f"{i} 与 {i+6} 都是质数")


# datas = []
# for i in range(2, 1000):
#     for j in range(2, i):
#         if i % j == 0:
#             break
#     else:
#         # print(f"{i}")
#         datas.append(i)
# # print(datas)
# for e in datas:
#     if e + 6 in datas:
#         print(e, e+6)


# 39.一直输入数字，直到数字之和为5的倍数，求输入数字的平均数

# total = 0
# count = 0
# while True:
#     value = input("输入数字")
#     value = int(value)
#     total += value
#     count += 1
#     if total % 5 == 0:
#         break
# print(total / count)


# 40.输入1 个正整数 n(n<=100)，计算并输出1/1＋1/2＋1/3＋……＋1/n 。

# value = input("输入数字")
# value = int(value)
# total = 0
# for i in range(1, value+1):
#     total += 1 / i
# print(total)


# 41.输入两个数，求两个数的最大公约数，最小公倍数
# value1 = int(input("输入数字"))
# value2 = int(input("输入数字"))
# max_value = value1 if value1 > value2 else value2
# min_value = value1 if value1 < value2 else value2
#
# current = max_value
# while True:
#     if current % value1 == 0 and current % value2 == 0:
#         print(current)
#         break
#     else:
#         current += 1
#
# current = min_value
# while True:
#     if value1 % current == 0 and value2 % current == 0:
#         print(current)
#         break
#     else:
#         current -= 1


# 42.已知四位数3025有一个特殊性质: 它的前两位数字30和后两位数字25的和是 55, 而	55的平方刚好等于该数(55*55=3025). 试编一程序打印所有具有这种性质的四位数.

# # 1209
# current = 1000
# while current < 10000:
#     # print(current)
#     prev = current // 100
#     last = current % 100
#     if (prev + last) ** 2 == current:
#         print(current)
#     current += 1


# current = 1000
# while current < 10000:
#     value = str(current)
#     prev = int(value[:2])
#     last = int(value[2:])
#     if (prev + last) ** 2 == current:
#         print(current)
#     current += 1


# 43.找到500到1000以内满足以下的质数对（前两个差值是第二个与第三个差值的一半）
# datas = []
# for i in range(500, 1000):
#     for j in range(2, i):
#         if i % j == 0:
#             break
#     else:
#         datas.append(i)
#
# print(datas)
# # 503, 509, 521   6 -- 12
# # 503, 521, 557  18 -- 36
#
# for i in range(len(datas)):
#     for j in range(i+1, len(datas)):
#         value = datas[j] - datas[i]  #  求差值
#         value *= 2  # 差值翻倍
#         value += datas[j]  # 求第二个数+翻倍后的差值得到第三个数
#         if value in datas:   # 判定第三个数是否在列表中
#             print(datas[i], datas[j], value)


# 44.将第一个字符串与第二个字符串进行拼接
# abcdefg  1234 拼接结果a4b3c2d1efg

# s0 = "abcdefg"
# s1 = "1234"
#
# s2 = ""
# for i in range(len(s0)):
#     s2 += s0[i]
#     if i < len(s1):
#         c = s1[len(s1) - 1 - i]
#         s2 += c
# print(s2)

# s0 = "abcdefg"
# s1 = "1234"
# s1 = s1[::-1]
# s2 = ""
# for i in range(len(s1)):
#     s2 += s0[i]
#     s2 += s1[i]
# s2 += s0[len(s1):]
# print(s2)

# 45.如何判断一个字符串是否为另一个字符串的子串（自己遍历，不使用index,find，in等方法）

# abcdefghijklmn
#   cdef

# s0 = "abcdefghijklmn"
# s1 = "cdef"
# for i in range(len(s0) - len(s1) + 1):
#     # print(s0[i])
#     for j in range(len(s1)):
#         # print(s1[j], s0[i+j])
#         if s1[j] != s0[i+j]:
#             break
#     else:
#         print(f"是子字符串")
#         break


# abcdefghijkl
#   cdef

# def is_sub(string, substring):
#     """
#     判定substring 是否是string 的子字符串
#     :return: 是子字符串返回True 否则返回False
#     """
#     for i in range(len(string) - len(substring) + 1):
#         for j in range(len(substring)):
#             if substring[j] != string[i + j]:
#                 break
#         else:
#             return True
#     return False
#
# print(is_sub("abcdefghijkl", "abcdef"))

# 44.编程实现如下图列出的图形。7行
# *       0
# ***     1
# *****   2
# ******* 3
# *****   3
# ***     2
# *       1

# 0
# 1
# 2
# 3
# 4
#
# 4
# 3
# 2
# 1

# def draw_n(n):
#     for i in range(n // 2 + (1 if n % 2 else 0)):
#         print((i*2+1) * "*")
#
#     for i in range(n // 2, 0, -1):
#         print((i*2-1) * "*")
#
# draw_n(70)


# 45.随机生成10个位于10-50之间的数字， 打印25以上与25以下平均数的差值

# random.seed(100)
#
# # print(random.random())
# # print(random.random())
# # print(random.random())
# # print(random.random())
# # print(random.random())
#
# def get_red(n, a, b, c):
#     total_up = []
#     total_down = []
#
#     for i in range(n):
#         value = random.randint(a, b)
#         if value >= c:
#             total_up.append(value)
#         else:
#             total_down.append(value)
#
#     return sum(total_up) / len(total_up) - sum(total_down) / len(total_down)
#
# print(get_red(10, 10, 50, 25))


# 46.斐波那契数列指的是这样一个数列：1，1，2，3，5，8，13，21，34，55，89...
# 求第n个数是几
# def get_n(n):
#     first = 1
#     second = 1
#     current = None
#     for i in range(3, n + 1):
#         current = first + second
#         first = second
#         second = current
#     return current
#
# print(get_n(5))


# for i in range(10):
#     for j in range(10):
#         if i == j or i + j == 9 or j == 9 or j == 0 or i == 0 or i == 9 or i >= j and i + j >= 9 or i <= j and i + j <= 9:
#             print("*", end="  ")
#         else:
#             print(" ", end="  ")
#
#     print()

# 47.计算二维列表中所有数字的平均数
# l0 = [
#     [1, 2, 3],
#     [4, 5, 6],
#     [7, 8, 9]
# ]
#
# total = 0
# count = 0
# for e in l0:
#     # print(e, type(e))
#     for e2 in e:
#         # print(e2)
#         total += e2
#         count += 1
# print(total / count)

# 48 编写一个程序，输入一个字符串，统计其中每个字符出现的次数
# def calc(string):
#     result = {}
#     for c in string:
#         if c in result:
#             result[c] += 1
#         else:
#             result[c] = 1
#     return result
#
#
# def main():
#     while True:
#         input_str = input("输入字符串")
#         if input_str == "exit":
#             break
#         else:
#             r = calc(input_str)
#             print(f"统计结果:{r}")
#
#
# main()

# 49 编写一个程序，输入一个列表和一个整数 n，将该列表中的所有元素都循环右移 n 位，并输出修改后的列表。
# [1,2,3,4,5,6,7]  3    [5,6,7,1,2,3,4]
# def main():
#     datas = []
#     for i in range(7):
#         value = input("输入数字")
#         datas.append(value)
#
#     n = input("输入偏移量")
#     n = int(n)
#     n = n % len(datas)
#     last = datas[-n:]
#     first = datas[:-n]
#     print(last+first)
#
# main()

# 50.找出一个二维数组每行的最大值
# [
#     [1, 5, 9],
#     [2, 3, 6],
#     [7, 5, 3]
# ]
# 输入 9 6 7

# l0 = [
#     [1, 5, 9],
#     [2, 3, 6],
#     [7, 5, 3]
# ]

# for e in l0:
#     print(max(e))

#
# for e in l0:
#     max_value = e[0]
#     for i in range(1, len(e)):
#         if max_value < e[i]:
#             max_value = e[i]
#     print(max_value)


# 51.找出一个二维数组每列的最大值
# [
#     [1, 5, 9],
#     [2, 3, 6],
#     [7, 5, 3]
# ]
# 输入 7 5 9
# l0 = [
#     [1, 5, 9],
#     [2, 3, 6],
#     [7, 5, 3]
# ]
# for i in range(len(l0)):
#     # print(l0[i])
#     max_value = None
#     for j in range(len(l0[i])):
#         # print(l0[i][j])
#         if max_value is None:
#             max_value = l0[j][i]
#         else:
#             if max_value < l0[j][i]:
#                 max_value = l0[j][i]
#     print(max_value)

# 52.对二维数组进行水平镜像
# [
# [1,2,3],
# [4,5,6],
# [7,8,9]
# ]
#
# [
# [3,2,1],
# [6,5,4],
# [9,8,7]
# ]

# l0 = [
#     [1, 2, 3],
#     [4, 5, 6],
#     [7, 8, 9]
# ]
# for e in l0:
#     # print(e)
#     for i in range(len(e) // 2):
#         # print(e[i],   e[ len(e) - 1 - i ])
#         temp = e[i]
#         e[i] =  e[ len(e) - 1 - i ]
#         e[len(e) - 1 - i] = temp
# print(l0)

# for e in l0:
#     e.reverse()

# for i in range(len(l0)):
#     l0[i] = l0[i][::-1]
#
# print(l0)

# l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# for i in range(len(l) // 2):
#     # print(l[i], l[len(l) - 1 - i])
#     temp = l[i]
#     l[i] = l[len(l) - 1 - i]
#     l[len(l) - 1 - i] = temp
# print(l)


# 53.对二维数组进行竖直镜像
# [
# [1,2,3],
# [4,5,6],
# [7,8,9]
# ]
#
# [
# [7,8,9],
# [4,5,6],
# [1,2,3]
# ]

#
# l = [
#     [1, 2, 3],
#     [4, 5, 6],
#     [7, 8, 9]
# ]
#
# for i in range(len(l)):
#     for j in range(len(l[i]) // 2):
#         print(l[j][i], l[len(l[i])-1-j][i])
#         # temp = l[j][i]
#         # l[j][i] = l[len(l[i])-1-j][i]
#         # l[len(l[i]) - 1 - j][i] = temp
#     # print()
# print(l)

# 54.随机生成10个位于10-50之间的数字,求10个数的平均数

# total = 0
# for i in range(10):
#     value = random.randint(10, 50)
#     total += value
# print(total / 10)


# 55.输入两个数，求两个数的最大公约数，最小公倍数
# input_a = int(input("输入数字"))
# input_b = int(input("输入数字"))
# max_value = input_a if input_a > input_b else input_b
# min_value = input_a if input_a < input_b else input_b

# current = min_value
# while True:
#     if input_a % current == 0 and input_b % current == 0:
#         print(current)
#         break
#     else:
#         current -= 1
#
# current = max_value
# while True:
#     if current % input_b == 0 and current % input_a == 0:
#         print(current)
#         break
#     else:
#         current += 1


# 56.删除指定列表中所有的奇数 [1,2,3,4,5,6,7,8,9]
# 结果 [2,4,6,8]

# l = [1, 1, 2, 3, 4, 7, 5, 6, 7, 8, 9]

# 遍历的过程中不要删除元素  必须删则倒着遍历  （删除一个元素会影响后续元素的索引，前面元素不影响）
# for i in range(len(l)-1, -1, -1):
#     if l[i] % 2:
#         l.remove(l[i])
#
# print(l)

# l0 = []
# for e in l:
#     if not e % 2:
#         l0.append(e)
#
# print(l0)

# 57.编写一个函数，接受一个整数参数 n，返回 n 的阶乘和。 5！+4！+3！+2！+1!s

# total = 0
# for i in range(1, 5 + 1):
#     mul = 1
#     for j in range(1, i + 1):
#         mul *= j
#     total += mul
# print(total)

# def get_sum(n):
#     total = 0
#     for i in range(1, n + 1):
#         total += get_mul(i)
#     return total
#
# # print(get_sum(5))
#
# def get_mul(n):
#     mul = 1
#     for i in range(1, n+1):
#         mul *= i
#     return mul
#
# # print(get_mul(5))
#
# print(get_sum(5))

# 一、封装函数求a, b之间所有奇数的和
# def get_sum(a, b):
#     current = a
#     total = 0
#     while current <= b:
#         total += current if current % 2 else 0
#         current += 1
#     return total
#
#
# print(get_sum(1, 5))

# 二、通过封装求和与求阶乘两个方法实现求 n的阶乘和
# def get_sum(n):
#     total = 0
#     for i in range(1, n + 1):
#         total += get_mul(i)
#     return total
#
#
# def get_mul(n):
#     total = 1
#     for i in range(1, n + 1):
#         total *= i
#     return total
#
#
# print(get_sum(5))

# 三、封装函数：可以判断一个数是否是质数

# def is_prime(n):
#     for i in range(2, n):
#         if n % i == 0:
#             break
#     else:
#         print(f"{n}是质数")
#
# is_prime(97)


# 五、编写函数求start到end以内所有的相差为step的素数对

# def is_prime(n):
#     for i in range(2, n):
#         if n % i == 0:
#             return False
#     else:
#         return True
#
#
# def get_prime_pairs(start, end, step):
#     datas = []
#     for i in range(start, end - step):
#         if is_prime(i) and is_prime(i+6):
#             datas.append([i, i+6])
#     return datas
#
#
# print(get_prime_pairs(1, 1001, 6))

# 六、编写函数返回斐波那契数列的第n个数
# 斐波那契数列指的是这样一个数列：1，1，2，3，5，8，13，21，34，55，89...


# def get_n(n):
#     first = 1
#     second = 1
#     current = None
#     if n == 1 or n == 2:
#         return 1
#     else:
#         for i in range(3, n+1):
#             current = first + second
#             first = second
#             second = current
#     return current
#
# print(get_n(11))


# def get_n(n):
#     if n == 1:
#         return 1
#     elif n == 2:
#         return 1
#     else:
#         return get_n(n-1) + get_n(n-2)
#
# print(get_n(11))

# 七、编写一个函数，接受一个数字n作为参数，该函数可以随机生成n个整数，并返回	所有整数的最大值

# def get_max(n):
#     max_value = None
#     for i in range(n):
#         value = random.randint(10, 100)
#         print(value)
#         if max_value is None:
#             max_value = value
#         else:
#             if max_value < value:
#                 max_value = value
#     return max_value
#
# print(get_max(10))


# 八、利用冒泡排序，与选择排序 对以下列表排序
#  [1, 3, 5, 7, 6, 2, 4, 8, 9]
# 冒泡排序
# 每轮得到一个最大的或者最小的放在开始

# l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
#
# # 如果有 n个元素 则需要比较n-1轮
# count = 0
# count2 = 0
# for i in range(len(l) - 1):
#     for j in range(i + 1, len(l)):
#         count += 1
#         if l[j] > l[i]:
#             temp = l[i]
#             l[i] = l[j]
#             l[j] = temp
#             count2 += 1
#     print(f"第{i}轮结束结果{l}")
#
# print(f"比较次数{count}, 交换次数{count2},  最终结果{l}")
# # 冒泡排序 缺点： 最不理想情况 比较n次 交换n次 （比如列表是升序， 最终需要降序排列）


# l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# # 选择排序，和冒泡排序非常相似  但是 先比较一轮 找到最大或最小的 最后在交换
#
#
# count = 0
# count2 = 0
# for i in range(len(l) - 1):
#     max_index = i
#     for j in range(i + 1, len(l)):
#         count += 1
#         if l[j] > l[max_index]:
#             max_index = j
#
#     if max_index != i:
#         count2 += 1
#         temp = l[i]
#         l[i] = l[max_index]
#         l[max_index] = temp
#     print(f"第{i} 轮排序结果{l}")
#
# print(f"比较次数{count}  交换次数{count2} 最终结果{l}")

# 算法

# count = 0
# count2 = 0
# l = [5, 2, 4, 6, 1, 5, 3, 9]
# for i in range(len(l)-1):
#     for j in range(i+1, len(l)):
#         count += 1
#         if l[j] > l[i]:
#             temp = l[j]
#             l[j] = l[i]
#             l[i] = temp
#             count2 += 1
#     print(f"第{i}轮比较结果{l}")
# print(l, f"比较次数{count}  交换次数{count2}")


# [1, 5, 4, 6, 2, 5, 3, 9]
#
# [1, 2, 5, 6, 4, 5, 3, 9]
#
# [1, 2, 3, 6, 5, 5, 4, 9]
#
# [1, 2, 3, 4, 6, 5, 5, 9]
#
# [1, 2, 3, 4, 5, 6, 5, 9]
#
# [1, 2, 3, 4, 5, 5, 6, 9]
#
# [1, 2, 3, 4, 5, 5, 6, 9]


# count = 0
# count2 = 0
# l = [5, 2, 4, 6, 1, 5, 3, 9]
# for i in range(len(l) - 1):
#     min_index = i
#     for j in range(i+1, len(l)):
#         # print(l[j], l[min_index])
#         count += 1
#         if l[j] < l[min_index]:
#             min_index = j
#     if min_index != i:
#         count2 += 1
#         temp = l[i]
#         l[i] = l[min_index]
#         l[min_index] = temp
#     print(f"第{i}轮 交换结果{l}")
#
# print(l, f"比较次数{count} 交换次数{count2}")

# [1, 2, 4, 6, 5, 5, 3, 9]
#
# [1, 2, 4, 6, 5, 5, 3, 9]
#
# [1, 2, 3, 6, 5, 5, 4, 9]
#
# [1, 2, 3, 4, 5, 5, 6, 9]
#
# [1, 2, 3, 4, 5, 5, 6, 9]
#
# [1, 2, 3, 4, 5, 5, 6, 9]
#
# [1, 2, 3, 4, 5, 5, 6, 9]

# 九、学习使用python乌龟绘图turtle模块完成基本图形的绘制

# import turtle
# print(turtle)
# import turtledemo
# print(turtledemo)


# import turtle
#
# turtle.setup(1000, 500)
# print(turtle.window_width(), turtle.window_height())
#
# turtle.bgcolor("grey")
# turtle.width(5)
# turtle.color("red", "pink")
# turtle.begin_fill()
# turtle.forward(200)
# turtle.left(90)
# turtle.forward(200)
# turtle.right(90)
# turtle.backward(200)
# turtle.right(90)
# turtle.forward(200)
# turtle.end_fill()
# # turtle.reset()
# turtle.up()
# turtle.forward(150)
# turtle.down()
# turtle.width(10)
# turtle.pencolor("yellow")
# turtle.fillcolor("green")
# turtle.setheading(135)
# turtle.begin_fill()
# turtle.circle(80)
# turtle.end_fill()
# turtle.up()
# turtle.goto(-100, 100)
# turtle.down()
#
#
# turtle.mainloop()


# 八.编写学生管理系统，实现以下需求  [{id:101, name:"abc", sex:1},{{id:101, name:"abc", sex:1},{{id:101, name:"abc", sex:1}]
# 输入数字1，添加学生信息（名字，年纪，性别）
# 输入数字2，查看所有学生信息
# 输入数字3，统计学生平均年纪
# 输入数字4，统计学生性别比例
# 输入数字5，退出系统


# students = [
#     # {"sid": 101, "name": "s0", "age": 20, "sex": "nv"},
#     # {"sid": 102, "name": "s1", "age": 15, "sex": "nan"},
#     # {"sid": 103, "name": "s2", "age": 22, "sex": "nan"},
# ]
#
# while True:
#     menu = """
# 输入数字1，添加学生信息（名字，年纪，性别）
# 输入数字2，查看所有学生信息
# 输入数字3，统计学生平均年纪
# 输入数字4，统计学生性别比例
# 输入数字5，退出系统
#     """
#     print(menu)
#     option = input("输入数字选择对应的操作")
#     if option not in [str(i) for i in range(1, 6)]:
#         print(f"输入数字不合法，只能输入1-5")
#     else:
#         if option == "1":
#             while True:
#                 while True:
#                     name = input("输入学生名字")
#                     if 2 <= len(name) <= 4:
#                         break
#                     else:
#                         print(f"名字长度不合法, 长度【2, 4】")
#
#                 while True:
#                     age = input("输入学生年纪")
#                     age = int(age)
#                     if 0 <= age <= 100:
#                         break
#                     else:
#                         print(f"年纪范围不合法，区间【0, 100】")
#
#                 while True:
#                     sex = input("输入学生性别")
#                     if sex in ["男", "女"]:
#                         break
#                     else:
#                         print(f"性别不合法，只能输入男, 女")
#
#                 sid = 101 if not students else students[-1]["sid"] + 1
#                 s = {
#                     "sid": sid,
#                     "name": name,
#                     "age": age,
#                     "sex": sex
#                 }
#                 students.append(s)
#                 print(f"添加学生{s}成功,目前共有学生{len(students)}")
#                 while True:
#                     option_1 = input("是否继续添加学生? 是(Y) 否(N)")
#                     if option_1 not in ["Y", "N"]:
#                         print(f"输入不合法， 只能输入Y,N")
#                     else:
#                         break
#                 if option_1 == "Y":
#                     pass
#                 elif option_1 == "N":
#                     break
#
#         elif option == "2":
#             for s in students:
#                 print(f"学生编号:{s['sid']}\t学生名:{s['name']}\t学生年纪:{s['age']}\t学生性别:{s['sex']}")
#         elif option == "3":
#             total = 0
#             for s in students:
#                 total += s["age"]
#             print(f"平均年纪:{total / len(students)}")
#
#
#         elif option == "4":
#             result = {}
#             for s in students:
#                 if s["sex"] not in result:
#                     result[s["sex"]] = 1
#                 else:
#                     result[s["sex"]] += 1
#             for k, v in result.items():
#                 print(f"性别:{k} 人数:{v} 占：{v / len(students) * 100}%")
#         elif option == "5":
#             break


# 九.编写学生管理系统，实现增删改查
# 输入数字1，添加学生信息（编号, 名字，年纪，性别）
# 第一个学生id为101 后续学生自动加1
# 输入数字2，查看所有学生信息
# 输入数字3，查看指定学生信息
# 输入学生id，显示对应学生信息
# 输入数字4，修改学生信息
# 输入学生id，输入学生新名字，新年纪，新性别
# 输入数字5，删除指定学生
# 输入学生id，删除指定学生
# 输入数字0，退出系统


import json
import os

datas = {
    "students": []
}


def show_main_menu():
    print("欢迎来到学生管理系统".center(30, "*"))
    info = """0. 退出程序
1. 添加学生
2. 删除学生
3. 修改学生信息
4. 查看指定学生详细信息
5. 查看所有学生列表"""
    print(info)


def show_sub_menu(menu):
    info = f"""0. 返回
1. {menu}"""
    print(info)


def get_user_input(options):
    while True:
        option = input("输入数字，选择对应的操作")
        if option not in options:
            print(f"输入不合法,只能输入{options}")
        else:
            return option


def get_student_name():
    while True:
        name = input("输入学生名字")
        if 2 <= len(name) <= 4:
            return name
        else:
            print(f"输入不合法,名字长度2-4")


def get_student_age():
    while True:
        age = input("输入学生年纪")
        age = int(age)
        if 0 <= age <= 30:
            return age
        else:
            print(f"输入不合法,年纪范围0-30")


def get_student_sex():
    while True:
        sex = input("输入学生性别")
        if sex in ["男", "女"]:
            return sex
        else:
            print(f"输入不合法,性别只能是男/女")


def add_student():
    while True:
        show_sub_menu("添加学生")
        option = get_user_input([str(i) for i in range(2)])
        if option == "0":
            break
        elif option == "1":
            s = {
                "sid": 101 if not datas["students"] else datas["students"][-1]["sid"] + 1,
                "name": get_student_name(),
                "age": get_student_age(),
                "sex": get_student_sex()
            }
            datas["students"].append(s)
            print(f"添加学生 {s} 成功, 现有学生{len(datas['students'])}个")
            save_data()


def remove_student():
    while True:
        show_sub_menu("删除学生")
        option = get_user_input([str(i) for i in range(2)])
        if option == "0":
            break
        elif option == "1":
            sid = input("输入学生id")
            sid = int(sid)
            for s in datas["students"]:
                if s["sid"] == sid:
                    datas["students"].remove(s)
                    print(f"删除id为{sid}的学生成功，剩余学生{len(datas['students'])}")
                    save_data()
                    break
            else:
                print(f"没有找到id为 {sid} 的学生")


def update_student():
    while True:
        show_sub_menu("修改学生信息")
        option = get_user_input([str(i) for i in range(2)])
        if option == "0":
            break
        elif option == "1":
            sid = input("输入学生id")
            sid = int(sid)
            for s in datas["students"]:
                if s["sid"] == sid:
                    s["name"] = get_student_name()
                    s["age"] = get_student_age()
                    s["sex"] = get_student_sex()
                    print(f"修改成功,学生信息{s}")
                    save_data()
                    break
            else:
                print(f"没有找到id为 {sid} 的学生")


def show_student_info():
    while True:
        show_sub_menu("查看学生信息")
        option = get_user_input([str(i) for i in range(2)])
        if option == "0":
            break
        elif option == "1":
            sid = input("输入学生id")
            sid = int(sid)
            for s in datas["students"]:
                if s["sid"] == sid:
                    print(f"找到id为{sid} 的学生,学生信息{s}")
                    break
            else:
                print(f"没有找到id为 {sid} 的学生")

def show_all_students():
    while True:
        show_sub_menu("查看所有学生信息")
        option = get_user_input([str(i) for i in range(2)])
        if option == "0":
            break
        elif option == "1":
            if datas["students"]:
                for s in datas["students"]:
                    print(f"学生信息{s}")
            else:
                print(f"还没有添加学生信息")


def load_data():
    global datas
    file_path = "./data.json"
    if os.path.exists(file_path):
        with open(file_path, "r") as f:
            datas = json.load(f)


def save_data():
    file_path = "./data.json"
    with open(file_path, "w") as f:
        json.dump(datas, f)

def main():
    load_data()
    while True:
        show_main_menu()
        main_option = get_user_input([str(i) for i in range(6)])
        if main_option == "0":
            break
        elif main_option == "1":
            add_student()
        elif main_option == "2":
            remove_student()
        elif main_option == "3":
            update_student()
        elif main_option == "4":
            show_student_info()
        elif main_option == "5":
            show_all_students()


main()
